//
//  WZSafeDict.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/4/5.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZSafeDict.h"

static const void * const WZSafeDictDispatchQueueSpecificKey = &WZSafeDictDispatchQueueSpecificKey;
@interface WZSafeDict ()

{
    dispatch_queue_t    _queue;
}
@end

@implementation WZSafeDict
- (instancetype)init
{
    self = [super init];
    if (self) {
        _queue = dispatch_queue_create([[NSString stringWithFormat:@"wzsafeDict.%@", self] UTF8String], NULL);
        dispatch_queue_set_specific(_queue, WZSafeDictDispatchQueueSpecificKey, (__bridge void *)self, NULL);
        self.safeDict = [NSMutableDictionary dictionary];
    }
    return self;
}



- (void)removeObjectForKey:(id)aKey
{
    dispatch_block_t block = ^{
        if (aKey) {
            [self.safeDict removeObjectForKey:aKey];
        }
    };
    
    if (dispatch_get_specific(WZSafeDictDispatchQueueSpecificKey)) {
        block();
    } else {
        dispatch_async(_queue, block);
    }

}
- (void)setObject:(id)anObject forKey:(id)aKey
{
    dispatch_block_t block = ^{
        if (aKey) {
            [self.safeDict setObject:anObject forKey:aKey];
        }
    };
    
    if (dispatch_get_specific(WZSafeDictDispatchQueueSpecificKey)) {
        block();
    } else {
        dispatch_async(_queue, block);
    }
}
- (void)removeAllObjects
{
    dispatch_block_t block = ^{
         [self.safeDict removeAllObjects];
    };
    
    if (dispatch_get_specific(WZSafeDictDispatchQueueSpecificKey)) {
        block();
    } else {
        dispatch_async(_queue, block);
    }

}
- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
{
    dispatch_block_t ablock = ^{
        [self.safeDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            block(key,obj,stop);
        }];

    };
    
    if (dispatch_get_specific(WZSafeDictDispatchQueueSpecificKey)) {
        ablock();
    } else {
        dispatch_async(_queue, ablock);
    }
}


@end
